<?php
/**
 * 钉钉登录插件 - 获取登录二维码
 */

session_start();
header('Content-Type: application/json; charset=utf-8');

// 读取配置
$configFile = __DIR__ . '/../../config.php';
$config = [];
if (file_exists($configFile)) {
    $config = include $configFile;
}

$dingtalkConfig = $config['plugins']['dingtalk'] ?? [];

if (!isset($dingtalkConfig['enabled']) || !$dingtalkConfig['enabled']) {
    echo json_encode([
        'success' => false,
        'message' => '钉钉登录插件未启用'
    ]);
    exit;
}

$appKey = $dingtalkConfig['app_key'] ?? '';
$redirectUri = $dingtalkConfig['redirect_uri'] ?? '';

if (empty($appKey) || empty($redirectUri)) {
    echo json_encode([
        'success' => false,
        'message' => '钉钉登录配置不完整'
    ]);
    exit;
}

// 生成 state 参数用于防止 CSRF 攻击
$state = bin2hex(random_bytes(16));
$_SESSION['dingtalk_state'] = $state;

// 构建钉钉扫码登录 URL
$qrcodeUrl = 'https://oapi.dingtalk.com/connect/qrconnect?' . http_build_query([
    'appid' => $appKey,
    'response_type' => 'code',
    'scope' => 'snsapi_login',
    'state' => $state,
    'redirect_uri' => $redirectUri
]);

echo json_encode([
    'success' => true,
    'qrcode_url' => $qrcodeUrl,
    'message' => '二维码生成成功'
]);
